package com.robaone.api.business;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.transform.Result;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXResult;
import javax.xml.transform.stream.StreamSource;

import org.apache.commons.io.IOUtils;
import org.apache.fop.apps.Fop;
import org.apache.fop.apps.FopFactory;
import org.apache.fop.apps.MimeConstants;
import org.json.JSONObject;
import org.json.XML;

public class PDFTransformer {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		try{
			if(args.length < 2){
				throw new Exception("not enough arguments");
			}
			ROTransformer trn = new ROTransformer(IOUtils.toString(new FileInputStream(new File(args[1]))));
			OutputStream out = new ByteArrayOutputStream();
			if(args.length > 2){
				FileOutputStream fout = new FileOutputStream(new File(args[2]+".tmp"));
				out = fout;
			}
			FileInputStream fin = new FileInputStream(new File(args[0]));
			trn.transformToStream(fin, out);
			InputStream in = null;
			if(args.length > 2){
				in = new FileInputStream(new File(args[2]+".tmp"));
			}else{
				in = new ByteArrayInputStream(((ByteArrayOutputStream)out).toByteArray());
			}
			FileOutputStream fout = null;
			try{
				fout = new FileOutputStream(new File(args[2]));
				FopFactory fopFactory = FopFactory.newInstance();
				TransformerFactory tFactory = TransformerFactory.newInstance();
				Fop fop = fopFactory.newFop(MimeConstants.MIME_PDF,fout);
				Transformer transformer = tFactory.newTransformer();
				Source src = new StreamSource(in);
				Result res = new SAXResult(fop.getDefaultHandler());
				transformer.transform(src,res);
				fout.flush();
			}finally{
				try{fout.close();}catch(Exception e){}
			}
		}catch(Exception e){
			e.printStackTrace();
		}
	}

}
